package netWork;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class MyUdpEchoClient {

    //网络编程接口套接字
    private DatagramSocket socket = null;

    //客户端IP地址
    private String serverIP = null;

    //客户端端口号
    private int serverPort = 0;

    //构造方法进行字段初始化
    public MyUdpEchoClient(String serverIP,int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;

        //socket 的初始化与其他字段不同
        socket = new DatagramSocket();
    }

    //客户端开始运行
    public void start() throws IOException {
        System.out.println("启动客户端");
        Scanner scanner = new Scanner(System.in);

        //利用 while 循环来持续发送请求
        while(true){

            System.out.println("->");

            //从控制台接受用户的输入
            String request = scanner.next();

            //构造出一个Udp请求发送给服务器
            DatagramPacket PacketRequest = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(this.serverIP),this.serverPort);
            //发送构造出的 Udp 请求数据报,通过 socket 来发送数据报
            socket.send(PacketRequest);

            //从服务器中读取响应
            DatagramPacket PacketResponse = new DatagramPacket(new byte[4096],4096);
            //同样,通过 socket 来接受服务器的响应
            socket.receive(PacketResponse);
            //构造一个响应,用于打印在控制台上
            String response = new String(PacketResponse.getData(),0,PacketResponse.getLength());

            //使响应发显示到控制台上
            System.out.println(response);
        }
    }

    //使客户端程序开始运行
    public static void main(String[] args) throws IOException {
        //先创建一个客户端的对象
        MyUdpEchoClient client = new MyUdpEchoClient("127.0.0.1",9090);
        //对象运行方法
        client.start();
    }
}
